<template>
    <div class="sector-card">
        <div class="card-header">
            <h3>板块资金流今日涨跌幅</h3>
        </div>
        <div class="card-body">
            <el-table :data="currentPageData" style="width: 100%" :show-header="true"
                :header-cell-style="tableConfig.headerCellStyle" :cell-style="tableConfig.cellStyle" border
                allow-drag-last-column :height="'auto'">
                <el-table-column prop="sectorName" label="板块名称" />
                <el-table-column prop="dailyChangePercent" label="涨跌幅" align="right">
                    <template #default="scope">
                        <div class="change-value" :class="{
                            increase: scope.row.dailyChangePercent > 0,
                            decrease: scope.row.dailyChangePercent < 0,
                        }">
                            {{ scope.row.dailyChangePercent }}%
                            <el-icon v-if="scope.row.dailyChangePercent > 0">
                                <CaretTop />
                            </el-icon>
                            <el-icon v-else>
                                <CaretBottom />
                            </el-icon>
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页控制 -->
            <div class="pagination-controls">
                <div class="pagination-buttons">
                    <el-button size="small" type="text" @click="prevPage" :disabled="currentPage === 1">
                        <ArrowLeft />
                    </el-button>

                    <div class="pagination-indicator">
                        <span v-for="(_, index) in totalPages" :key="index" :class="{
                            active: currentPage === index + 1,
                            clickable: true,
                        }" class="dot" @click="goToPage(index + 1)"></span>
                    </div>

                    <el-button size="small" type="text" @click="nextPage" :disabled="currentPage === totalPages">
                        <ArrowRight />
                    </el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, inject } from 'vue';
import {
    CaretTop,
    CaretBottom,
    ArrowLeft,
    ArrowRight,
} from '@element-plus/icons-vue';
import { tableStyle as tableConfig } from '../utils/tableConfig.js';
import { getSectors } from '../api/api.js';

// 注入 Dashboard 提供的暂停更新状态控制变量
const shouldPauseUpdates = inject('shouldPauseUpdates', ref(false));

// 分页状态
const currentPage = ref(1);
const pageSize = ref(6);

// 板块数据（默认空，待后端填充）
const sectorData = ref([]);

const fetchSectorData = async () => {
    try {
        const response = await getSectors();
        // 如果 getSectors 抛出了整个 response 对象，我们也尝试拿 data
        const res = response.data
            ? response
            : {
                data: response.data,
                code: response.code,
                message: response.message,
            };
        if (res.code === '200' && res.message === 'success') {
            sectorData.value = res.data;
        } else {
            console.error('获取板块数据失败:', res.message);
        }
    } catch (error) {
        // 如果被拦截器 reject 的是整个 response，也要处理
        if (error && error.code === '200' && error.message === 'success') {
            sectorData.value = error.data;
        } else {
            console.error('请求板块数据出错:', error);
        }
    }
};

// 带检查的数据获取函数
const fetchDataWithCheck = () => {
    // 只有在不暂停更新时才获取新数据
    if (!shouldPauseUpdates.value) {
        fetchSectorData();
    } else {
        console.log('板块资金流数据更新已暂停');
    }
};

// 总页数
const totalPages = computed(() =>
    Math.ceil(sectorData.value.length / pageSize.value)
);

// 当前页数据
const currentPageData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    return sectorData.value.slice(start, start + pageSize.value);
});

// 翻页逻辑
const nextPage = () => {
    currentPage.value =
        currentPage.value < totalPages.value ? currentPage.value + 1 : 1;
};
const prevPage = () => {
    currentPage.value =
        currentPage.value > 1 ? currentPage.value - 1 : totalPages.value;
};
// 修改页面切换处理函数
const goToPage = pageNumber => {
    if (pageNumber >= 1 && pageNumber <= totalPages.value) {
        // 用户手动切换页面时，暂时停止自动翻页
        if (autoSwitchTimer) {
            clearInterval(autoSwitchTimer);
            autoSwitchTimer = null;
        }

        currentPage.value = pageNumber;

        // 手动翻页后延迟恢复自动翻页
        setTimeout(() => {
            startAutoSwitch();
        }, 10000); // 用户操作后10秒恢复自动翻页
    }
};

// 添加响应式页面大小设置函数
const adjustPageSizeByScreenHeight = () => {
    const height = window.innerHeight;

    // 根据屏幕高度动态调整每页显示条数
    if (height >= 1800) {
        pageSize.value = 8; // 4K屏幕
    } else if (height >= 1200) {
        pageSize.value = 7; // 大屏幕
    } else {
        pageSize.value = 6; // 默认屏幕
    }
};

// 页面加载时请求数据
onMounted(() => {
    // 首先调整页面大小
    adjustPageSizeByScreenHeight();

    fetchSectorData();

    // 数据加载后启动自动翻页（延迟启动以确保数据已加载）
    setTimeout(() => {
        startAutoSwitch();
    }, 1000);

    // 设置定期刷新数据（每30秒刷新一次）
    dataRefreshTimer = setInterval(() => {
        fetchDataWithCheck();
    }, 30000);
});

// 添加组件卸载前清除定时器
onBeforeUnmount(() => {
    if (autoSwitchTimer) {
        clearInterval(autoSwitchTimer);
        autoSwitchTimer = null;
    }

    if (dataRefreshTimer) {
        clearInterval(dataRefreshTimer);
        dataRefreshTimer = null;
    }
});

// 添加定时器变量
let autoSwitchTimer = null;
let dataRefreshTimer = null;

// 启动自动翻页
const startAutoSwitch = () => {
    // 清除可能存在的定时器
    if (autoSwitchTimer) {
        clearInterval(autoSwitchTimer);
        autoSwitchTimer = null;
    }

    // 仅当有多页时启动自动翻页
    if (totalPages.value > 1) {
        autoSwitchTimer = setInterval(() => {
            // 只有在不暂停更新时才执行翻页
            if (!shouldPauseUpdates.value) {
                nextPage();
            }
        }, 5000); // 每5秒切换一页
    }
};
</script>

<style scoped>
@import '../assets/css/style.css';

.sector-card {
    background-color: #001e4a;
    border-radius: 5px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    height: 100%;
}

.change-value {
    display: flex;
    align-items: center;
    justify-content: flex-end;
}

.increase {
    color: #f56c6c;
}

.decrease {
    color: #67c23a;
}

@media (min-height: 1200px) {
    .card-header h3 {
        font-size: 22px;
    }

    .card-body {
        padding: 20px;
    }
}

@media (min-height: 1800px) {
    .card-header h3 {
        font-size: 26px;
    }

    .card-body {
        padding: 25px;
    }
}
</style>